import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  // 路由懒加载：页面路径切换到相应组件，才去加载对应组件代码
  // 优点：让首页加载文件体积更小，打开更快
  {
    path: '/',
    redirect: '/home',
    component: () => import('@/views/layout'),
    children: [
      { path: 'home', component: () => import('@/views/home') },
      { path: 'user-info', component: () => import('@/views/userInfo') },
      { path: 'user-avatar', component: () => import('@/views/userAvatar') },
      { path: 'user-pwd', component: () => import('@/views/userPwd') },
      { path: 'art-cate', component: () => import('@/views/artCate') },
      { path: 'art-list', component: () => import('@/views/artList') }
    ]
  },
  { path: '/register', component: () => import('@/views/register') },
  { path: '/login', component: () => import('@/views/login') },
  { path: '/home', component: () => import('@/views/home') }
]

const router = new VueRouter({
  routes
})
// 定义路由白名单(可以直接跳转)
const whiteList = ['/login', '/register']
// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 登录(有token)
  if (store.state.token) {
    next()
  } else {
    // 未登录(无token)，如果要去的页面是白名单页面，可以直接跳转
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 如果不是白名单页面，则要跳转到登录页面
      next('login')
    }
  }
})
export default router
